﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using OConf.Entity;
using OConf.Model.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace OConf.Service
{
    /// <summary>
    ///Version
    /// </summary>
    public class VersionsService
    {
        private readonly IConfiguration Configuration;

        public VersionsService(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        /// <summary>
		/// 是否存记录
		/// </summary>
		/// <returns>存在返回True,不存在或异常返回fasle</returns>	
		public bool Exists(string ID)
        {
            bool isExists = false;
            using (var db = new MyDBContext(Configuration))
            {
                isExists = db.Versions.Any(t => t.ID == ID);
            }
            return isExists;
        }

        /// <summary>
		/// 增加一条数据
		/// </summary>
		public bool Insert(VersionsEntity model)
        {
            bool isAdd = false;
            using (var db = new MyDBContext(Configuration))
            {
                db.Versions.Add(model);
                int rows = db.SaveChanges();
                isAdd = rows > 0;
            }
            return isAdd;
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(VersionsEntity model)
        {
            bool isUpdate = false;
            using (var db = new MyDBContext(Configuration))
            {
                db.Versions.Update(model);
                int rows = db.SaveChanges();
                isUpdate = rows > 0;
            }
            return isUpdate;
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(string ID)
        {
            bool isDelete = false;
            using (var db = new MyDBContext(Configuration))
            {
                VersionsEntity model = new VersionsEntity() { ID = ID };
                db.Versions.Remove(model);
                int rows = db.SaveChanges();
                isDelete = rows > 0;
            }
            return isDelete;
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public VersionsEntity GetModel(string ID)
        {
            VersionsEntity model = null;
            using (var db = new MyDBContext(Configuration))
            {
                model = db.Versions.Where(w => w.ID == ID).FirstOrDefault();
            }
            return model;
        }

        /// <summary>
        /// 获取过期的版本信息（获取最近20条之外的版本信息）
        /// </summary>
        /// <returns></returns>
        public List<string> GetExpiredIDs(string namespaceId)
        {
            List<string> list = new List<string>();
            using (var db = new MyDBContext(Configuration))
            {
                list = db.Versions.Where(w => w.NameSpaceID == namespaceId)
                    .OrderByDescending(o=>o.Createtime)
                    .Select(w => w.ID)
                    .Skip(20).Take(100)
                    .ToList();
            }
            return list;
        }

        /// <summary>
        /// 删除版本信息和配置历史信息
        /// </summary>
        /// <param name="verId"></param>
        public void DeleteVersionAndConfigByTran(string verId)
        {
            using (var db = new MyDBContext(Configuration))
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        db.Versions.Where(w => w.ID == verId)
                            .ExecuteDelete();

                        db.ConfigInfoHistory.Where(w => w.VersionID == verId)
                            .ExecuteDelete();

                        tran.Commit();
                    }
                    catch
                    {
                        tran.Rollback();
                        throw;
                    }
                }
            }
        }

        /// <summary>
        /// 获取最新版本信息
        /// </summary>
        /// <param name="projectID"></param>
        /// <param name="namespaceId"></param>
        /// <returns></returns>
        public VersionsEntity GetLatestVersion(string projectID, string namespaceId)
        {
            VersionsEntity model = null;
            using (var db = new MyDBContext(Configuration))
            {
                model = db.Versions.Where(w => w.ProjectID == projectID && w.NameSpaceID == namespaceId)
                    .OrderByDescending(o => o.Createtime)
                    .FirstOrDefault();
            }
            return model;
        }

        /// <summary>
        /// 根据命名空间id获取配置历史信息
        /// </summary>
        /// <param name="namespaceId"></param>
        /// <returns></returns>
        public List<VersionsEntity> GetListByNameSpaceId(string namespaceId)
        {
            List<VersionsEntity> list = new List<VersionsEntity>();
            using (MyDBContext db = new MyDBContext(Configuration))
            {
                list = db.Versions.Where(w => w.NameSpaceID == namespaceId)
                    .OrderByDescending(o => o.Createtime)
                    .Select(w => new VersionsEntity()
                    {
                        ID = w.ID,
                        VersionNo = w.VersionNo,
                        Createtime = w.Createtime
                    }).ToList();
            }
            return list;
        }

        /// <summary>
        /// 版本信息回滚
        /// </summary>
        /// <param name="newVersion"></param>
        /// <param name="configInfoHistories"></param>
        /// <param name="configInfos"></param>
        public void VersionRollBackByTran(VersionsEntity newVersion, List<ConfigInfoHistoryEntity> configInfoHistories, List<ConfigInfoEntity> configInfos)
        {
            int row = 0;
            using (MyDBContext db = new MyDBContext(Configuration))
            {
                using (var tran = db.Database.BeginTransaction())
                {
                    try
                    {
                        //生成新的版本信息
                        db.Versions.Add(newVersion);
                        row = db.SaveChanges();
                        if (row <= 0)
                        {
                            throw new Exception($"生成新的版本信息失败,{JsonConvert.SerializeObject(newVersion)}");
                        }

                        //新增配置历史信息
                        db.ConfigInfoHistory.AddRange(configInfoHistories);
                        db.SaveChanges();

                        //删除旧的配置信息
                        db.ConfigInfo.Where(w => w.NameSpaceID == newVersion.NameSpaceID)
                            .ExecuteDelete();

                        //新增配置信息
                        db.ConfigInfo.AddRange(configInfos);
                        db.SaveChanges();

                        //修改命名空间发布状态为已发布
                        row = db.CNameSpace.Where(w => w.ID == newVersion.NameSpaceID)
                            .ExecuteUpdate(x => x.SetProperty(p => p.IsPublish, true));
                        if (row <= 0)
                        {
                            throw new Exception($"修改命名空间发布状态失败,NameSpaceId:{newVersion.NameSpaceID}");
                        }

                        tran.Commit();
                    }
                    catch
                    {
                        tran.Rollback();
                        throw;
                    }
                }
            }
        }
    }
}